package com.example.userservice.interceptor;

import com.example.userservice.entity.Log;
import com.example.userservice.entity.User;
import com.example.userservice.service.UserService;
import com.example.userservice.util.LogHelper;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.LocalDateTime;

@Component
@RocketMQTransactionListener
public class UserTxListener implements RocketMQLocalTransactionListener {

    @Autowired
    private LogHelper logHelper;

    @Autowired
    private UserService userService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        User user = (User) arg;
        String ip = (String) msg.getHeaders().get("ip");
        try {
            user.setGmtCreate(Timestamp.valueOf(LocalDateTime.now()));
            if (!userService.save(user)) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            Log log = logHelper.buildLog(user.getUserId(), "register", ip, user);
            logHelper.printLog(log);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String userName = (String) msg.getHeaders().get("userName");
        boolean exists = userService.lambdaQuery().eq(User::getUserName, userName).one() != null;
        return exists ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK;
    }
}
